<?php
// version 0.1 vom 18.7.11
// author: Burkhart Holznagel
// GNU GPL v2
// based on : http://www.ajaxlines.com/ajax/stuff/article/how_to_create_a_simple_webbased_chat_application.php
ini_set('session.use_trans_sid', 1);
session_start(); 
if(isset($_GET['sound'])){
    if ($_SESSION['sound'] == "0") $_SESSION['sound'] = "1"; else $_SESSION['sound'] = "0";
}
if(isset($_GET['logout'])){	
	//Simple exit message
	$fp = fopen("log.html", 'a');
	fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
	fclose($fp);
	unset($_SESSION['name']);
	unset($_SESSION['toggle']);
	session_destroy();
	header("Location: index.php"); //Redirect the user
	exit();
}

if(isset($_GET['clearchat'])){
    	$fp = fopen("log.html", 'w+');
    	fclose($fp);
}

function loginForm(){
	echo'
	<div id="loginform">
	<form name="myForm" action="index.php" method="post">
		<p>Please enter your name to continue:</p>
		<label for="name">Name:</label>
		<input type="text" name="name" id="name" />
		<input type="submit" name="enter" id="enter" value="Enter" />
	</form>
	</div>
	';
}

if (isset($_POST['radio'])){
    if($_POST['radio'] == "0")	$_SESSION['textfile'] = "family.txt";
    else	{
	if($_POST['radio'] == "1")	$_SESSION['textfile'] = "eat.txt";
	else
	if($_POST['radio'] == "2")	$_SESSION['textfile'] = "bed.txt";
	    }
}

if(isset($_POST['mysave']))	{
    $file = fopen($_SESSION['textfile'], "r+") or exit("Unable to open file!".$_SESSION['textfile']);
    for ($i=0; $i <  $_SESSION['fileLines']; $i++)  	$text[$i] = fgets($file,72);
    fclose($file);
    $file = fopen($_SESSION['textfile'], "w+") or exit("Unable to open file!".$_SESSION['textfile']);
    $i=$_POST['mysave'];
    $rev= strrev( $text[$i]);
    if ( "$rev{0}" == "\n" )$text[$i]=$_POST['mytext']; else $text[$i]=$_POST['mytext']."\n";
    for ($i=0; $i < $_SESSION['fileLines']; $i++)  	fputs($file,$text[$i],72);
    fclose($file); 
}

if(isset($_POST['enter'])){
	if($_POST['name'] != "")
		$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
	else	
		echo '<span class="error">Please type in a name</span>';
}
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My personal chat</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<link rel="shortcut icon" type="image/x-icon" href="/perchat/myicon.jpg">
</head>
<body onLoad="pageScroll()">
<audio id="audio" src="crossing.wav" preload="auto" autobuffer >
</audio>
	<script language="JavaScript">
	
	
/*document.write("Offizieller Name des Browsers: "+ navigator.appName + "<br>");
document.write("Spitzname des Browsers: " + navigator.appCodeName + "<br>");
document.write("Version: " + navigator.appVersion +"<br>");
document.write("HTTP-Identifikation des Browsers: " + navigator.userAgent +"<br>");
document.write("Plattform: " + navigator.platform +"<br>");
document.write("Eingestellte Sprache des Browsers: " + navigator.language +"<br>");
*/
// -->

</script>

<script type="text/javascript">

function pageScroll() {
    	window.scrollBy(0,150); // horizontal and vertical scroll increments
//    	scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
	 $("#chatbox").animate({ scrollTop: 1500 }, 'normal');
}

</script>
<?php
if(!isset($_SESSION['name'])){
    $_SESSION['textfile'] = "family.txt";
    $_SESSION['fileLines'] = 9;
    $_SESSION['sound']="0";
    loginForm();
    }
else	{
    $file = fopen($_SESSION['textfile'], "r") or exit("Unable to open file!".$_SESSION['textfile']);
    for ($i=0; $i < $_SESSION['fileLines']; $i++)	$text[$i] = fgets($file,72);
    fclose($file);  
?>
<div id="wrapper">
	<div id="menu">
		<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p><br>
	<table  width="100%"> <tr>
	<th>
	<p class="clearchat"><a id="clear" href="#">Clear Chat</a></p>
	</th>
	
	<script type="text/javascript">
	var sound = "<?php echo $_SESSION['sound']; ?>";
	if ( (navigator.appCodeName == "Mozilla") ||navigator.appCodeName == "Safari" )	{ // my sound doesnt work with IE ?
		if (sound == "0" )
		    document.write("<th><p class=\"sound\"><a id=\"sound\" href=\"#\">Sound If Chat Message</a></p></th>");
		else	
		    document.write("<th><p class=\"sound\"><a id=\"sound\" href=\"#\">No Sound If Chat Message</a></p></th>");
	}
	</script>
	<th>
		<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
	</th>
	</tr></table>
		<div style="clear:both"></div>
	</div>	
    <script type="text/javascript">  
    var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
//    mobile = 1;
    if (mobile) {  document.write("<div id=\"chatbox-smartphone\">");
    }  
    else	{
	document.write("<div id=\"chatbox\">");
    }
</script>
	<?php
	if(file_exists("log.html") && filesize("log.html") > 0){
		$handle = fopen("log.html", "r");
		$contents = fread($handle, filesize("log.html"));
		fclose($handle);
		echo $contents;
	}
	?>
	</div>
	
<form name="message" action="">
		<input name="usermsg" type="text" id="usermsg" size="63" value=""/>
		<input name="submitmsg" type="submit"  id="submitmsg" style="color:#2862A1;" value="send" />
</form>
<table>
<?php
for ( $i=0; $i < $_SESSION['fileLines']; $i++ )      {
echo "<form name=\"myrow".$i."\" action=\"index.php\" method=\"post\">"; 
echo "<tr><th><button name=\"mysave\" id=\"mysave".$i."\" type=\"submit\"   value= \"$i\" >change</button></th>";
echo "<th><input name=\"mytext\" id=\"mytext".$i."\" type=\"text\"  size= \"33\" value=\"";echo $text[$i]; echo "\"></th>";
echo "<th><button name=\"mybutton".$i."\" id=\"button".$i."\" type=\"button\" onclick=\"mysubmit($i)\">tochat"."</button></th></tr>";
echo "</form>";
}
?>
</table>
<?php
echo '<form action="index.php" method="post">';
if ($_SESSION['textfile'] == "family.txt")
    echo '<p> <input type="radio" name="radio" value="0" checked onclick="submit()" > Familie';
else
    echo '<p> <input type="radio" name="radio" value="0" onclick="submit()" > Familie';
if ($_SESSION['textfile'] == "eat.txt")
    echo '<input type="radio" name="radio" value="1" checked onclick="submit()" > Essen und Trinken';
else
    echo '<input type="radio" name="radio" value="1" onclick="submit()" > Essen und Trinken';
if ($_SESSION['textfile'] == "bed.txt")
    echo '<input type="radio" name="radio" value="2" checked onclick="submit()"> Bett und Schlafen</p>';
else
    echo '<input type="radio" name="radio" value="2" onclick="submit()"> Bett und Schlafen</p>';
echo '</form>';
?>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
    
    var before;
	//If user submits the form
	$("#submitmsg").click(function(){	
		var clientmsg = $("#usermsg").val();
		$.post("post.php", {text: clientmsg});				
		$("#usermsg").attr("value", "");
		return false;
	});
	//Load the file containing the chat log
	
	function loadLog(){
	      var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
//mobile =1;
	      if (mobile) { 
		    
		var oldscrollHeight = 1000 - 20;//$("#chatbox-smartphone").attr("scrollHeight") - 20;
		$.ajax({
			url: "log.html",
			cache: false,
			success: function(html){
				$("#chatbox-smartphone").html(html); //Insert chat log into the #chatbox div				
				//var newscrollHeight = $("#chatbox-smartphone").attr("scrollHeight") - 20;
			//	if(newscrollHeight > oldscrollHeight){
					$("#chatbox-smartphone").animate({ scrollTop: 1000+20 }, 'normal'); //Autoscroll to bottom of div
			//	}
		  	},
		});
    }  
    else	{
		    
		var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
		$.ajax({
			url: "log.html",
			cache: false,
			success: function(html){
				$("#chatbox").html(html); //Insert chat log into the #chatbox div				
				var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
				if(newscrollHeight > oldscrollHeight){
					$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
				}
		  	},
		});
	
    }
    
        var after = $("div").length;
if (typeof before == "undefined") {
before= after;
  
}
if (before < after)	{
      var thissound=document.getElementById('audio');
     var hitSound = new Audio('default_alarm.wav');
//hitSound.play();
<?php
	if ($_SESSION['sound'] == "1")	{
 // echo '  hitSound.play();';	// linux+firefox
	 echo 'thissound.play();';		// tested only linux + firefox and chrome, apple os + safari
	// echo "$(\"spam\").text(before + \"  \" + after);";
}
?>
}
   
before=after;
	}
	setInterval (loadLog, 2500);	//Reload file every 2.5 seconds

	//If user wants to end session
	$("#exit").click(function(){
		var exit = confirm("Are you sure you want to end the session?");1
		if(exit==true){window.location = 'index.php?logout=true';}		
	});
	$("#clear").click(function(){
		var clear = confirm("Are you sure you want to clear the chat?");1
		if(clear==true){window.location = 'index.php?clearchat=true';}		
	});
	$("#sound").click(function(){
	    window.location = 'index.php?sound=1';
	});
});
</script>
<?php
}
?>
<script type="text/javascript">
function mysubmit(nr)	{ 
    var clientmsg = $("#mytext"+nr).val();
 if (clientmsg != "")	{
	$.post("post.php", {text: clientmsg});				
	document.message.usermsg.focus();
	document.message.usermsg.select();
	CopiedTxt = document.selection.createRange();
	CopiedTxt.execCommand("Copy"); // doesnt work with firefox
 }
    return true;
}
</script>

</body>
</html>
